using MediatR;
using Microsoft.Data.SqlClient;
using PiggyBankCashFlowApi.Delegate.command;
using PiggyBankCashFlowApi.Exception;
using PiggyBankCashFlowApi.Ext;
using PiggyBankCashFlowApi.Repo;
using PiggyBankCashFlowApi.Repo.Entity;

namespace PiggyBankCashFlowApi.Delegate.Handler;

public class UpdateCashFlowHandler(
    CashFlowRepo repo,
    IHttpContextAccessor accessor,
    ILogger<UpdateCashFlowHandler> logger):IRequestHandler<UpdateCashFlowCommand,CashFlowEntity>
{
    public async Task<CashFlowEntity> Handle(UpdateCashFlowCommand request, CancellationToken cancellationToken)
    {
        var entity = await repo.GetCashFlowAsync(request.Id);
        if (entity == null)
        {
            throw new ResourceNotFoundException($"Resource not found for Id: {request.Id}.");
        }
            
        var userId = accessor.GetUserId();
        if (!entity.UserId.ToString().Equals(userId))
        {
            throw new ForbiddenException("You are not authorized to update this cash flow.\n" +
                                            $"User Id {userId} vs cash flow owner {entity.UserId}");
        }

        var rowsAffected = await repo.UpdateCashFlowAsync(
            request.Id, request.Subject, request.Amount, request.Direction,
            request.Comment,request.PicUrl,request.TransferDate);
        if (rowsAffected > 0)
        {
            return (await repo.GetCashFlowAsync(request.Id))!;
        }

        throw new DbOpNotAcceptedException("Opt not accepted: cash flow could not be updated.");
    }
}